<?php
/**
 * 
 * 
 */	
class Module_SendController extends  Zend_Controller_Action {
	public function init() {
        //Load cau hinh thu muc trong file config.ini
        $app = Zend_Registry::get('App');
        //Lay duong dan thu muc goc (path directory root)
        $this->view->baseUrl = $baseUrl = $this->_request->getBaseUrl() . "/public/";
        $result = array(
                    array($baseUrl.'lib-js/module/Module_Send.js','js')
					,array($baseUrl.'css/themes/blitzer/jquery-ui-1.8.14.custom.css','css')
					,array($baseUrl.'lib-js/ui/jquery.ui.datepicker-vi.js','js')
                    ,array($baseUrl.'lib-js/tabs.js','js')
                    ,array($baseUrl.'lib-js/system/upload/css/bootstrap.css','css')
                    ,array($baseUrl.'lib-js/system/upload/css/jquery.fileupload.css','css')
                    ,array($baseUrl.'lib-js/system/upload/css/jquery.fileupload-ui.css','css')
                    ,array($baseUrl.'lib-js/system/upload/js/vendor/jquery.ui.widget.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/tmpl.min.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/jquery.iframe-transport.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/jquery.fileupload.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/jquery.fileupload-process.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/jquery.fileupload-ui.js','js')
                );
        if ($this->_request->isXmlHttpRequest()){
            Zend_Layout::startMvc(array(
                'layoutPath' => $app->layout,
                'layout' => 'partial'
            ));
            $this->view->arrJsCss = Zend_Json::encode($result);
        }else{
            //Cau hinh cho Zend_layout
            Zend_Layout::startMvc(array(
                'layoutPath' =>$app->layout,
                'layout' => 'index'
            ));
            //Load ca thanh phan cau vao trang layout (index.phtml)
            $response = $this->getResponse();
           
            //Dinh nghia current modul code
            $this->view->currentModulCode = $this->_request->getParam('controller');
            $this->view->currentModulCodeForLeft = $this->_request->getParam('action');
            $this->view->postHeader = Clound_String::registerFile($result);
            // echo  Clound_String::registerFile($result); die;
            //Hien thi file template
            $response->insert('menu', $this->view->renderLayout('menu.phtml', './application/layout/scripts/'));     //Hien thi header 
			$response->insert('submenu', $this->view->renderLayout('submenu.phtml', './application/layout/scripts/')); 
            $response->insert('footer', $this->view->renderLayout('footer.phtml', './application/layout/scripts/'));   //Hien thi f
        }
    }
    public function indexAction() {
	
    }
	/**
	*	Lấy dữ liệu cho màn hình danh sách
	*
	*/
    public function dataAction(){
        $objDocSend = new Module_Models_Docsend();
		$session = new Clound_Session();
        $parames = $this->_request->getParams();
		$parames['Status'] = 'DA_BAN_HANH';
		$parames['StaffID'] = Zend_Auth::getInstance()->getIdentity()->StaffID;
		$parames['Permistion'] = $session->checkPermission('160010');
		$parames['Role'] = 'GUI_NHAN_VB';
		$parames['RoleStatus'] = '';
        $data = $objDocSend->getAllDocsend($parames);
        echo Zend_Json::encode($data);
        die;
    }
    public function completedAction() {
		
    }
    public function completeddataAction(){
        $objDocSend = new Module_Models_Docsend();
		$session = new Clound_Session();
        $parames = $this->_request->getParams();
		$parames['Status'] = 'CHO_PHAT_HANH';
		$parames['StaffID'] = Zend_Auth::getInstance()->getIdentity()->StaffID;
		$parames['Permistion'] = $session->checkPermission('160010');
		$parames['Role'] = 'GUI_NHAN_VB';
		$parames['RoleStatus'] = '';
        $data = $objDocSend->getAllDocsend($parames);
        echo Zend_Json::encode($data);
        die;
    }	
    /**
     * @see : Màn hình thêm, sửa văn bản
     *
     */
    public function addAction() {
        if (!$this->_request->isXmlHttpRequest()) {
            return $this->_helper->redirector('index');
        }
		$this->view->addHelperPath('Clound/Xml/Helper/', 'Clound_Xml_Helper');
        $SendID = $this->_request->getParam('SendID');
        //Gan gia tri mac dinh cho cac Input
		if($SendID!=''){
			$objDocSend = new Module_Models_Docsend();
			$model = $objDocSend->selectRow($SendID);
			//Thong tin file dinh kem
			$model['RecordID'] = $SendID.'.docsend.SEND';
			//Lay thong tin nguoi nhan
			$modelStaff = new Module_Models_DraffStaff();
			$sRole = 'GUI_NHAN_VB';
			$model['HandleStaffList'] = implode(',',$modelStaff->getStaffByRole($SendID,$sRole));
			//2014-09-01 00:00:00
			$objDate = new Clound_Datetime();
			$objDate->set($model['SendDate'],'yyyy-MM-dd HH:mm:ss');
			$model['SendDate'] = $objDate->ToDdMMyyyy();
		}else{
			$objDate = new Clound_Datetime();
			$sSendDate = $objDate->ToDdMMyyyy();
			$sSendYear = $objDate->ToYear();
			$autoIncement = new Module_Models_Increment();
            $increment = $autoIncement->getNumber($sSendYear,'SEND');			
			$model = array(
				'SendDate' 	=> $sSendDate,
				'NumberMain' 	=> $increment,
			);
		}
		$session = new Clound_Session();
		//Lay can bo co quyen du thao vb
		$session->getsetStaffsByPermission('160011');
		//Lay can bo co quyen ky duyet vb
		$session->getsetStaffsByPermission('160013');
		//Lay can bo co quyen nhan vb
		$session->getsetStaffsByPermission('160014');
        // File xml mô tả form
        $filexml = 'xml/module/send/formfield_add_edit.xml';
        $xmlObj = new Clound_Xml($filexml,$model);
        $formObj = $xmlObj->formfieldGenerate();
        $this->view->form=$formObj;
    }

    public function releaseAction() {
        if (!$this->_request->isXmlHttpRequest()) {
            return $this->_helper->redirector('index');
        }
		$this->view->addHelperPath('Clound/Xml/Helper/', 'Clound_Xml_Helper');
        $SendID = $this->_request->getParam('SendID');

		$objDocSend = new Module_Models_Docsend();
		$model = $objDocSend->selectRow($SendID);
		//Thong tin file dinh kem
		//$model['RecordID'] = $SendID.'.docsend.SEND';
		$model['RecordID'] = $SendID.'.docsend.DRAFF';
		//Lay thong tin nguoi nhan
		$model['HandleStaffList'] = '';
		//2014-09-01 00:00:00
		$objDate = new Clound_Datetime();
		$model['SendDate'] = $objDate->ToDdMMyyyy();
		
		$session = new Clound_Session();
		//Lay can bo co quyen du thao vb
		$session->getsetStaffsByPermission('160011');
		//Lay can bo co quyen ky duyet vb
		$session->getsetStaffsByPermission('160013');
		//Lay can bo co quyen nhan vb
		$session->getsetStaffsByPermission('160014');
        // File xml mô tả form
        $filexml = 'xml/module/send/formfield_add_edit.xml';
        $xmlObj = new Clound_Xml($filexml,$model);
        $formObj = $xmlObj->formfieldGenerate();
        $this->view->form=$formObj;
    }
	
    public function getnumberAction() {
		$objDate = new Clound_Datetime($this->_request->getParam('date'), 'dd/MM/yyyy');
		$sSendYear = $objDate->ToYear();
		$autoIncement = new Module_Models_Increment();
		$increment = $autoIncement->getNumber($sSendYear,'SEND');
		echo $increment;exit;
    }
    /**
     * @see : Màn hình thêm, sửa văn bản
     *
     */
    public function ropAction() {
        if (!$this->_request->isXmlHttpRequest()) {
            return $this->_helper->redirector('index');
        }
		$this->view->addHelperPath('Clound/Xml/Helper/', 'Clound_Xml_Helper');
        $SendID = $this->_request->getParam('SendID');
        //Lay thong tin co ban
		$objDocSend = new Module_Models_Docsend();
		$model = $objDocSend->selectRow($SendID);
		$objDate = new Clound_Datetime();
		$objDate->set($model['SendDate'],'yyyy-MM-dd HH:mm:ss');
		$model['SendDate'] = $objDate->ToDdMMyyyy();
		$fileObj = new Clound_File(null,false);
		$model['Subject'] = $fileObj->SumContenAndFile('Subject','SendID','docsend','SEND',$model);			
		$this->view->model = $model;
		//Cap nhat thong tin nhan vb
		$iStaff = Zend_Auth::getInstance()->getIdentity()->StaffID;
		$modelStaff = new Module_Models_DraffStaff();
		$sRole = 'GUI_NHAN_VB';
		$modelStaff->updateRopReceived($SendID,$iStaff,$sRole);
    }
    public function ropdataAction() {
		//Lay thong tin nguoi nhan
        $SendID = $this->_request->getParam('SendID');		
		$modelStaff = new Module_Models_DraffStaff();
		$sRole = 'GUI_NHAN_VB';
		$model = $modelStaff->getRopReceived($SendID,$sRole);
        echo Zend_Json::encode($model);
        die;
    }
	/*
	*	Lưu văn bản
	*
	*/
    public function saveAction() {
        $model = new Module_Models_Docsend();
        //Lay cac tham so cua form
		$iSendID = (int)$this->_request->getParam('SendID');
        $sDocType = $this->_request->getParam('DocType');
		$objDate = new Clound_Datetime($this->_request->getParam('SendDate'), 'dd/MM/yyyy');
        $sSendDate = $objDate->ToYYyymmdd();
		$sSendYear = $objDate->ToYear();
        $iNumberMain = (int)trim($this->_request->getParam('NumberMain'));
        $sNumberAdd = trim($this->_request->getParam('NumberAdd'));
        $sSymbol = trim($this->_request->getParam('Symbol'));
        $sSubject = trim($this->_request->getParam('Subject'));
        $sNature = $this->_request->getParam('Nature');
		$sEmergency = $this->_request->getParam('Emergency');
		$sReplyDoc = (int)$this->_request->getParam('ReplyDoc');
		
		$oCloundPublic = new Clound_Public();
		$iStaffDraf = (int)$this->_request->getParam('StaffDraf');
		$staff = $oCloundPublic->getDepFromStaff($iStaffDraf);
		$sPositionName = $staff['Name'];
		$iDepartmentDraf = $staff['UnitID'];

		$iApprovedID = (int)$this->_request->getParam('StaffSign');
		$staff = $oCloundPublic->getDepFromStaff($iApprovedID);
		$sApprovedName = $staff['Name'];		
		
		$sXmlData = $this->_request->getParam('XmlData');
		$sTemp = '';
		$sReceivedInfo = $this->_request->getParam('OtherReceived');
		//Mang gia tri
        $data = array(
            "SendID"			=> 	$iSendID,
            "ReceivedID"		=> 	$sReplyDoc,
            "NumberMain"		=> 	$iNumberMain,
            "NumberAdd"			=> 	$sNumberAdd,
            "Symbol"			=> 	$sSymbol,
            "DocType"			=> 	$sDocType,
            "SendDate"			=> 	$sSendDate,
			"SendYear"			=>	$sSendYear,
            "Nature"			=>	$sNature,
			"Emergency"			=>	$sEmergency,
			"Subject"			=>	$sSubject,
			"XmlData"			=>	$sXmlData,
			"Status"			=>	'DA_BAN_HANH',
			"Details"			=>	0,
			"Temp"				=>	$sTemp,
			"StaffID"			=>	$iStaffDraf,
			"PositionName"		=>	$sPositionName,
			"DepartmentID"		=>	$iDepartmentDraf,
			"ApprovedID"		=>	$iApprovedID,
			"ApprovedName"		=>	$sApprovedName,
			"ReceivedInfo"		=>	$sReceivedInfo,
			"OwnerCode"			=>	'TPVT',
        );
        $errors = array();
		$sFileIdList = '';
		$sFileNameList = '';
		//var_dump($data);exit;
        if($model->isValid($data)){
            if ($iSendID === 0) {
                $model->insert($data);
				$iSendID = $model->getAdapter()->lastInsertId();
            } else {
                $where="SendID ='$iSendID'";
                $model->update($data,$where);
            }
        }else{
            array_push($errors,array('Code'=>'Số văn bản đã tồn tại!'));
        }
		if(!isset($errors['Code'])){
			//Cap nhat so vb
			$autoIncement = new Module_Models_Increment();
            $increment = $autoIncement->getNumber($sSendYear,'SEND');
            if($increment <= $data['NumberMain']){
                $arrInput = array(
                        'Number'=>(int)$data['NumberMain'] + 1
                    );
                $autoIncement->update($arrInput,"Type='SEND' And Years='$sSendYear'");
            }
			//Can bo cho y kien
			$sHandleStaffList = $this->_request->getParam('HandleStaffList');
			//Xoa he nhung nguoi khong duoc chon
			$modelStaff = new Module_Models_DraffStaff();
			//Insert nguoi moi
			$sRole = 'GUI_NHAN_VB';
			$modelStaff->deleteNotIn($iSendID,$sHandleStaffList,$sRole);
			if($sHandleStaffList){
				$count = sizeof($sHandleStaffList);
				for ($i = 0; $i < $count; $i++) {
					//Kiem tra co ton tai hay ko
					if($modelStaff->isValid($iSendID,$sHandleStaffList[$i],$sRole)){
						$staff = $oCloundPublic->getDepFromStaff($sHandleStaffList[$i]);
						//Mang gia tri
						$data = array(
							"DraffHandleStaffID"			=> 	0,
							"DocID"							=> 	$iSendID,
							"DepartmentID"					=> 	$staff['UnitID'],
							"StaffID"						=> 	$sHandleStaffList[$i],
							"PositionName"					=> 	$staff['Name'],
							"Role"							=> 	$sRole,
							"ReceiveDate"					=> 	$sSendDate,
							"Status"						=> 	'CHO_XU_LY'
						);
						$modelStaff->insert($data);
					}
				}
			}
			//
			$fileObj = new Clound_File(null,false);
			$modelFile = new System_Models_File();
			//Lay file dinh kem
			$arrSign = $model->selectRow($iSendID);				
			$sFileIdList = $arrSign['FileID'];
			$sFileNameList = $arrSign['FileName'];
			//Xoa file
			$sDeleteFileList = $this->_request->getParam('deleteFileList');
			//echo $sDeleteFileList;exit;
			if ($sDeleteFileList != '') {
				$arrFileIdList = explode(',', $sFileIdList);
				$arrFileNameList = explode('!#!', $sFileNameList);			
				$arrDeleteFile = explode('!#~$|*', $sDeleteFileList);
				$count = sizeof($arrDeleteFile);
				for ($i = 0; $i < $count; $i++) {
					$arrTemp = explode('.', $arrDeleteFile[$i]);
					$arrFile = $modelFile->getFileView($arrTemp);
					$delete = $modelFile->deleteRows($arrFile['FileID']);
					$fileObj->_deleteFileAttach($arrFile['FileName']);
					$arrFileIdList = array_diff($arrFileIdList, array($arrFile['FileID']));
					$arrFileNameList = array_diff($arrFileNameList, array($arrFile['FileName']));
				}
				$sFileIdList = implode(',',$arrFileIdList);
				$sFileNameList = implode('!#!', $arrFileNameList);				
			}
			//echo $sFileNameList;exit;
			//File dinh kem
			$sAttachfile = $this->_request->getParam('attachfile');
			$arrFileNameList = array();
			if ($sAttachfile != '') {
				$arrFileNameList = $fileObj->_uploadFileAttachList($sAttachfile);
			}
			$count = sizeof($arrFileNameList);
			if($count){
				for ($i = 0; $i < $count; $i++) {
					$sFileId = '';
					//Mang gia tri
					$data = array(
						"FileID"			=> 	0,
						"RecordID"			=> 	$iSendID,
						"RecordType"		=> 	'SEND',
						"FileType"			=> 	strtolower(pathinfo($arrFileNameList[$i], PATHINFO_EXTENSION)),
						"FileName"			=> 	$arrFileNameList[$i],
						"TableName"			=> 	'docsend'
					);
					$modelFile->insert($data);
					$sFileId = $modelFile->getAdapter()->lastInsertId();
					if($sFileIdList==''){
						$sFileIdList = $sFileId;
						$sFileNameList = $arrFileNameList[$i];
					}else{
						$sFileIdList .= ','.$sFileId;
						$sFileNameList .= '!#!'.$arrFileNameList[$i];
					}
				}
			}
			//if($sFileIdList!=''){
				//Update file id
				$data = array(
							"SendID"		=> 	$iSendID,
							"FileID"		=> 	$sFileIdList,
							"FileName"		=> 	$sFileNameList
						);
				$where="SendID ='$iSendID'";
				$model->update($data,$where);
			//}			
		}
        echo Zend_Json::encode($errors);
        die;
    }

    /**
     * @see : Thuc hien viec xoa Mot hoac Nhieu văn bản đi
     */
    public function deleteAction() {
        $model = new Module_Models_Docsend;
        $sDocSendIDList = $this->_request->getParam('ListIDs');
        echo Zend_Json::encode($model->deleteRows($sDocSendIDList));
        die();
    }
}?>
